/**
 *  *2010-5-22 上午11:24:39  add 
 */
package com.base.myproject.client.HR.setting;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.ui.BaseBusiLeftPanel;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGridPanel;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * 社保基数
 * 
 * @author Administrator 2010-5-22 javazgw@gmail.com
 */
public class Social_base extends BaseJDBCPanel {
	PagingToolBar toolBar1 = null;
	
	BaseStore<BusiObject> mstore = null;
	DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd");
	Button inport = new Button("自动生成社保基数");
	private TextField<String> search = null;
	private Button btnSearch = null;
	private TextField<String> C_num2 = null;
	
	public Social_base() {
		init();
		
	}

	public void init() {
		toolBar1 = new PagingToolBar(50);
		
		this.add(initWeigetx());

		registerMainStore(mstore);
		registerStore(mstore);
		registerStore(dstore);
	}

	public void complete() {
		 super.complete();
		 getToolbarll().add(inport);
		 inport.addListener(Events.Select, getListener());
	}

	private Widget initWeigetx() {
		VerticalPanel v = new VerticalPanel();
		HorizontalPanel h= new HorizontalPanel();
		v.setSpacing(1);
		v.setHorizontalAlign(HorizontalAlignment.LEFT);
		h.setVerticalAlign(VerticalAlignment.TOP);
		h.add(CreateCcodeLeftPanel());
		v.add(createForm());
		
		ContentPanel cp = new ContentPanel();
		cp.setHeaderVisible(false);
		cp.add(createGrid());
		cp.setBottomComponent(toolBar1);
		v.add(cp);
		h.add(v);
		h.setSpacing(2);
		return h;
	}
	public ContentPanel CreateCcodeLeftPanel() {
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		ColumnConfig cname = new ColumnConfig("name", "名称", 200);
		TextField<String> gnametext = new TextField<String>();

		columns.add(cname);
		ColumnModel cm = new ColumnModel(columns);

		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("name");
		type.getField("name").setType(String.class);
		type.addField("Reportdate");
		type.getField("Reportdate").setType(Date.class);
		type.addField("Adjustdate");
		type.getField("Adjustdate").setType(Date.class);
		type.addField("vprepare");
		type.getField("vprepare").setType(String.class);
		type.addField("busistatus");
		type.getField("busistatus").setType(String.class);
		type.addField("createdate");
		type.getField("createdate").setType(Date.class);
		type.addField("modifydate");
		type.getField("modifydate").setType(Date.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("mark");
		type.getField("mark").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_social_base");
		info.setKeyname(new String[] { "icode" });
		info.setSql("select * from hr_social_base");

		BaseBusiLeftPanel<BusiObject> basbusileftpanel = new BaseBusiLeftPanel<BusiObject>(
				columns, type, info);
		mstore = basbusileftpanel.getStore();
		basbusileftpanel.getGrid().setWidth("260");
		setMaincomponent(basbusileftpanel.getGrid());
		return basbusileftpanel.getPanel();
	}
	

	BaseFormPanel form = null;

	BaseFormPanel createForm() {
		BaseFormPanel form = new BaseFormPanel(mstore);
		TableLayout tl = new TableLayout(9);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);

		form.add(new Label("名称:"), td);
		C_num2 = new TextField<String>();
		C_num2.setWidth(100);
		C_num2.setName("name");
		form.add(C_num2, td);
		form.add(new Label("申报日期:"), td);
		DateField C_data3 = new DateField();
		C_data3.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		C_data3.setName("Reportdate");
		C_data3.setWidth(100);
		form.add(C_data3, td);
		form.add(new Label("生效日期:"), td);
		DateField C_data4 = new DateField();
		C_data4.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-M-d"));
		C_data4.setName("Adjustdate");
		C_data4.setWidth(100);
		form.add(C_data4, td);
		
		form.add(new Label("姓名："),td);
		search = new TextField<String>();
		search.setWidth(100);
		form.add(search,td);
		btnSearch = new Button("查找");
		btnSearch.addListener(Events.OnClick, getListener());
		form.add(btnSearch,td);

		form.inited();
		return form;
	};
	
	BaseStore<BusiObject> dstore = null;
	BaseStore<BusiObject> getStore(){
	if(dstore==null) 
	{
		createdStore();
	}
	return dstore;}
	BaseStore<BusiObject> createdStore(){
	ModelType type = new ModelType();
	type.setRoot("records");
	type.setRecordName("record");
	type.setTotalName("totle");
	type.addField("icode");
	type.getField("icode").setType(Long.class);
	type.addField("upcode");
	type.getField("upcode").setType(Long.class);
	type.addField("bcode");
	type.getField("bcode").setType(String.class);
	type.addField("socialbase");
	type.getField("socialbase").setType(Double.class);
	StoreInfo info = new StoreInfo();
	info.setTablename("hr_social_basedetail");
	info.setKeyname(new String[] { "icode"});
	info.setSql("select icode,bcode,upcode,socialbase from hr_social_basedetail where upcode='{icode}'");
	info.setParent(mstore);// 关联主表
	info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
	info.setLinkparent_chile_columns(new String[] { "upcode" });// 关联主表字段 子表
	  dstore = new BaseStore<BusiObject>(type, info);
	  dstore.setToolBar(toolBar1);
	 return dstore;}

	

	BaseGridPanel gridpanel=null;
	BaseGridPanel createGrid(){
	CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
	List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
	columns.add(cbs.getColumn());

	ColumnConfig C3 = new ColumnConfig("bcode", "人员", 120);
	BaseComboBoxForm<BaseModelData> bsb2 = new BaseComboBoxForm<BaseModelData>("bcode","employno %2B bname","v_bcode2job","",true);
	C3.setRenderer(bsb2);
	C3.setEditor(bsb2.getCelEditor());
	columns.add(C3);
	
	ColumnConfig C4 = new ColumnConfig("socialbase", "社保基数", 80);
	NumberField C_num4 = new NumberField();
	C_num4.setPropertyEditorType(Long.class);
	C4.setEditor(new CellEditor(C_num4));
	columns.add(C4);

	ColumnModel cm = new ColumnModel(columns);
	gridpanel = new BaseGridPanel(getStore(), cm,true,true);
	cbs.setSelectionMode(SelectionMode.SINGLE);
	gridpanel.getBg().setSelectionModel(cbs);
	gridpanel.getBg().setBorders(false);
	gridpanel.getBg().setHeight(380);
	
	return gridpanel ;}
	
	BaseComboBoxForm<BaseModelData> group1;
	BaseComboBoxForm<BaseModelData> group2;
	void inport()
	{
		final Dialog d = new Dialog();
		FormPanel bf = new FormPanel() ;
		bf.setLabelWidth(100);
		bf.setHeaderVisible(false);
		bf.setBodyBorder(false);
		final DateField df = new DateField();
		df.getPropertyEditor().setFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		df.setFieldLabel("日期");
		
		group1 = new BaseComboBoxForm<BaseModelData>();
		group1.setFieldLabel("入职日期>=");
		group1.clearInvalid();
		group1.addListener(Events.Change, getListener());
		ListStore attendancedStore = new ListStore();
        List list = new Vector();
        
        ModelData type1 = new BaseModelData();
        type1.set("name", "去年平均");
        type1.set("value", "1");
        list.add(type1);
        
        ModelData type2 = new BaseModelData();
        type2.set("name", "最近十二个月平均");
        type2.set("value", "2");
        list.add(type2);
        
        ModelData type3 = new BaseModelData();
        type3.set("name", "入职当月");
        type3.set("value", "3");
        list.add(type3);
        
        attendancedStore.add(list);
        group1.setStore(attendancedStore);
        group1.setTriggerAction(TriggerAction.ALL);
        group1.setDisplayField("name");
        group1.setValueField("value");
		
		
        group2 = new BaseComboBoxForm<BaseModelData>();
		group2.setFieldLabel("入职日期<");
		group2.clearInvalid();
		group2.addListener(Events.Change, getListener());
		ListStore attendancedStore2 = new ListStore();
        List list2 = new Vector();
        
        ModelData type_1 = new BaseModelData();
        type_1.set("name", "去年平均");
        type_1.set("value", "1");
        list2.add(type_1);
        
        ModelData type_2 = new BaseModelData();
        type_2.set("name", "最近十二个月平均");
        type_2.set("value", "2");
        list2.add(type_2);
        
        ModelData type_3 = new BaseModelData();
        type_3.set("name", "入职当月");
        type_3.set("value", "3");
        list2.add(type_3);
        
        attendancedStore2.add(list);
        group2.setStore(attendancedStore2);
        group2.setTriggerAction(TriggerAction.ALL);
        group2.setDisplayField("name");
        group2.setValueField("value");
        
        
		bf.add(df);
		bf.add(group1);
		bf.add(group2);

		d.add(bf);
		
		d.setWidth(380);
		d.setHeight(280);
		d.setHeading("社保基数");
		d.setButtons(Dialog.OKCANCEL);
		d.show();
		
		df.addListener(Events.Changed, new Listener<BaseEvent>(){

			@Override
			public void handleEvent(BaseEvent be) {
				
				if(df.getValue()!=null){
					group1.setFieldLabel("入职日期>="+dtf.format(df.getValue()));
					group2.setFieldLabel("入职日期<"+dtf.format(df.getValue()));
				}
			}
			
			
		});

		
		d.getButtonById(Dialog.OK).addSelectionListener(new SelectionListener<ButtonEvent>(){
			@Override
			public void componentSelected(ButtonEvent ce) {
				DateTimeFormat dateFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
				final String date =df.getRawValue(); //dtf.format(df.getValue());
				final String curicode =  mstore.getValue("icode").toString();
				final String requestDate = dateFormat.format((Date)mstore.getValue("Reportdate"));
				if(date.equals("") || group1.getValue() == null || group2.getValue() == null ){
					MessageBox.alert("提示", "信息填写不够完整！", null);
				}else{
					d.getButtonById(Dialog.OK).setEnabled(false);
					MessageBox.confirm("提示	", "重新自动生成社保基数会删除之前的数据,是否继续进行?", new Listener<MessageBoxEvent> (){
						public void handleEvent(MessageBoxEvent be) {
							if(be.getButtonClicked().getText().equals(GXT.MESSAGES.messageBox_yes())){//选择同意后	
								String deleteSql = "delete hr_social_basedetail where upcode = '" + curicode + "'";
								
								//--年平均
								String sql1 = "insert into hr_social_basedetail (upcode,socialbase,bcode)  " + 
											"select '"+curicode+"' as upcode,round(avg(a.amount),0),a.bcode from ( " + 
											"select a.bcode, sum(a.amount) amount  " + 
											"from hr_salary a, hr_salary_main_c b, bcode_job c " + 
											"where a.upcode=b.code and a.bcode = c.bcode and exists (select 1 from hr_salary_item where a.allowanceno_ = code and ifsocial=1)  " + 
											"and employstatus = '在职' and entrydate >= '"+date+"'  " + 
											"and convert(varchar(7),b.end_time,120) between convert(varchar(4),DATEADD(year, -1,'"+requestDate+"'),120) + '-01' and convert(varchar(4),DATEADD(year, -1,'"+requestDate+"'),120) + '-12'  " + 
											" group by a.bcode,b.end_time,b.start_time " + 
											") as a group by bcode";
								//--12个月平均
								String sql2 = "insert into hr_social_basedetail (upcode,socialbase,bcode)  " + 
											"select '"+curicode+"' as upcode,round(avg(a.amount),0),a.bcode from ( " + 
											"select a.bcode, sum(a.amount) amount  " + 
											"from hr_salary a, hr_salary_main_c b, bcode_job c " + 
											"where a.upcode=b.code and a.bcode = c.bcode and exists (select 1 from hr_salary_item where a.allowanceno_ = code and ifsocial=1)  " + 
											"and employstatus = '在职' and entrydate >= '"+date+"'  " + 
											"and convert(varchar(7),b.end_time,120) between convert(varchar(7),DATEADD(month, -12,'"+requestDate+"'),120) and convert(varchar(7),DATEADD(month, -1,'"+requestDate+"'),120)  " + 
											" group by a.bcode,b.end_time,b.start_time " + 
											") as a group by bcode";
								//--最近一个月
								String sql3 = "insert into hr_social_basedetail (upcode,socialbase,bcode)  " + 
											"select '"+curicode+"' as upcode, round(sum(a.amount),0) amount,a.bcode  " + 
											"from hr_salary a, hr_salary_main_c b, bcode_job c " + 
											"where a.upcode=b.code and a.bcode = c.bcode and exists (select 1 from hr_salary_item where a.allowanceno_ = code and ifsocial=1)  " + 
											"and employstatus = '在职' and entrydate >= '"+date+"'  " + 
											"and convert(varchar(7),b.end_time,120) = convert(varchar(7),entrydate,120) " + 
											" group by a.bcode";
								//--年平均
								String sql4 = "insert into hr_social_basedetail (upcode,socialbase,bcode)  " + 
												"select '"+curicode+"' as upcode,round(avg(a.amount),0),a.bcode from ( " + 
												"select a.bcode, sum(a.amount) amount  " + 
												"from hr_salary a, hr_salary_main_c b, bcode_job c " + 
												"where a.upcode=b.code and a.bcode = c.bcode and exists (select 1 from hr_salary_item where a.allowanceno_ = code and ifsocial=1)  " + 
												"and employstatus = '在职' and entrydate < '"+date+"'  " + 
												"and convert(varchar(7),b.end_time,120) between convert(varchar(4),DATEADD(year, -1,'"+requestDate+"'),120) + '-01' and convert(varchar(4),DATEADD(year, -1,'"+requestDate+"'),120) + '-12' " + 
												" group by a.bcode,b.end_time,b.start_time " + 
												") as a group by bcode";
								//--12个月平均
								String sql5 = "insert into hr_social_basedetail (upcode,socialbase,bcode)  " + 
												"select '"+curicode+"' as upcode,round(avg(a.amount),0),a.bcode from ( " + 
												"select a.bcode, sum(a.amount) amount  " + 
												"from hr_salary a, hr_salary_main_c b, bcode_job c " + 
												"where a.upcode=b.code and a.bcode = c.bcode and exists (select 1 from hr_salary_item where a.allowanceno_ = code and ifsocial=1)  " + 
												"and employstatus = '在职' and entrydate < '"+date+"'  " + 
												"and convert(varchar(7),b.end_time,120) between convert(varchar(7),DATEADD(month, -12,'"+requestDate+"'),120) and convert(varchar(7),DATEADD(month, -1,'"+requestDate+"'),120)  " + 
												" group by a.bcode,b.end_time,b.start_time " + 
												") as a group by bcode";
								//--最近一个月
								String sql6 = "insert into hr_social_basedetail (upcode,socialbase,bcode)  " + 
												"select '"+curicode+"' as upcode, round(sum(a.amount),0) amount,a.bcode  " + 
												"from hr_salary a, hr_salary_main_c b, bcode_job c " + 
												"where a.upcode=b.code and a.bcode = c.bcode and exists (select 1 from hr_salary_item where a.allowanceno_ = code and ifsocial=1)  " + 
												"and employstatus = '在职' and entrydate < '"+date+"'  " + 
												"and convert(varchar(7),b.end_time,120) = convert(varchar(7),entrydate,120) " + 
												" group by a.bcode";
								
								CommandSyncContainer list = new CommandSyncContainer();
								CommandSyncsql cses = new CommandSyncsql();
								cses.setContinueorrollback(false);
								cses.getV().add(deleteSql);
				
								if(group1.getValue().get("value").toString()!="0" || group1.getValue().get("value").equals(null)){
									String group_id=group1.getValue().get("value").toString();
									if(group_id.equals("1")){
										cses.getV().add(sql1);
									}else if(group_id.equals("2")){
										cses.getV().add(sql2);
									}else if(group_id.equals("3")){
										cses.getV().add(sql3);
									}
								}
								if(group2.getValue().get("value").toString()!="0" || group2.getValue().get("value").equals(null)){
									String group2_id=group2.getValue().get("value").toString();
									if(group2_id.equals("1")){
										cses.getV().add(sql4);
									}else if(group2_id.equals("2")){
										cses.getV().add(sql5);
									}else if(group2_id.equals("3")){
										cses.getV().add(sql6);
									}
								}
							
								list.add(cses);
								if(cses.getV().size()<=0){
									MessageBox.alert("警告", "没有选择任何条件!", null);
									return ;
								}
									
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
								.create(com.base.myproject.client.tools.GreetingService.class);
								greetingService.SendCommandSync(list,
								new AsyncCallback<CommandSyncReturnObject>() {
				
									@Override
									public void onFailure(Throwable caught) {
										MessageBox.alert("错误", "网络连接失败", null);
										d.getButtonById(Dialog.OK).setEnabled(true);
									}
				
									@Override
									public void onSuccess(CommandSyncReturnObject result) {
										if (result.isB()) {
											Info.display("", "成功");
											d.hide();
											 String sql = dstore.getStoreinfo().getSql();
											 dstore.getStoreinfo().setSql(dstore.getSqlnow());
											 dstore.reload();
											 dstore.getStoreinfo().setSql(sql);
											
										} else {
											MessageBox.alert("错误", "" + result.getMessage(),
													null);
											
											d.getButtonById(Dialog.OK).setEnabled(true);
										}
				
									}
				
								});
								
							}else{//否的时候
								d.hide();
							}
						}		
					});	
				}
			}});
			d.getButtonById(Dialog.CANCEL).addSelectionListener(new SelectionListener<ButtonEvent>(){
				@Override
				public void componentSelected(ButtonEvent ce) {
					d.hide();
				}
			});
	}
	
	
	
	int sync = 0;
	Listener<BaseEvent> defaultlistener;

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}

		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							if (be.getSource().equals(inport)) {
								inport(); 	
							}
						}
						else if(be.getType() == Events.OnClick){
							if(be.getSource().equals(btnSearch)){
								String name = search.getRawValue();
								String oldSql = gridpanel.getBg().getStore().getStoreinfo().getSql();
								String sql = "select hr_social_basedetail.* from hr_social_basedetail,v_bcode2job where hr_social_basedetail.bcode=v_bcode2job.bcode and upcode="+mstore.getValue("icode");
								if (!name.equals("")) {
									sql += " and (bname like '%25"+name+"%25' or employno like '%25"+name+"%25')";
								}
								gridpanel.getBg().getStore().getStoreinfo().setSql(sql);
								gridpanel.getBg().getStore().reload();
								gridpanel.getBg().getStore().getStoreinfo().setSql(oldSql);
							}
						}
						else if (be.getType() == Events.Change) {
							if (be.getSource().equals("")) {
								
							}
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}

}
